package com.soft.one.db;

import com.soft.one.entity.User;
import com.soft.one.exception.MyException;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class UserDb {

    //存放人员账号信息
    private static List<User> userList = new ArrayList<>();

    public static void loadData(){
        //加载数据
        File file = new File("./files/user.txt");
        try {

            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            if(file.exists()){

                String lineInfo = "";
                while(lineInfo != null){
                    lineInfo = bufferedReader.readLine();
                    if(lineInfo != null){
                        //解析用户信息
                        String[] s = lineInfo.split(" ");
                        User user = new User();
                        user.setUsername(s[0]);
                        user.setPassword(s[1]);
                        user.setEmail(s[2]);
                        user.setPhone(s[3]);
                        user.setDesc(s[4]);
                        userList.add(user);
                    }
                }
            }
        } catch (Exception e) {
            throw new MyException("加载账号信息出错");
        }
    }

    private UserDb(){

    }

    public User getUserByUsername(String username) {
        //账号不能空
        if(userList.isEmpty()) {
            throw new MyException("账号为空");
        }
        //在账号列表中查询
        for (User user : userList) {
            if(username.equals(user.getUsername())){
                return user;
            }
        }
        return null;
    }




    public static List<User> getUserList() {
        return userList;
    }
}
